layui.use(['layer', 'form', 'table', 'ztree', 'laydate', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    var layer = layui.layer;
    var $ZTree = layui.ztree;
    var laydate = layui.laydate;

    /**
     * 商品信息表管理
     */
    var HxBasicGoods = {
        tableId: "hxBasicGoodsTable",    //表格id
        condition: {
            goodsBigtypedictId: "",
        }
    };
    // 获取当前时间
    function getCurrentDate() {
        return new Date();
    }

// 获取7天前的时间
    function getSevenDaysAgoDate() {
        var date = new Date();
        date.setDate(date.getDate() - 7);
        return date;
    }

// 判断日期是否在7天内
    function isWithinLastSevenDays(date) {
        var currentDate = getCurrentDate();
        var sevenDaysAgoDate = getSevenDaysAgoDate();
        var targetDate = new Date(date);
        return targetDate >= sevenDaysAgoDate && targetDate <= currentDate;
    }

    /**
     * 初始化表格的列
     */
    HxBasicGoods.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {align: 'center', toolbar: '#tableBar', title: '操作', width: 120},
            {align: 'center', toolbar: '#tableBar2', title: '图片', width: 60},
            {field: 'goodsCustomerName', sort: true, title: '客户'},
            {
                field: 'goodsName',
                sort: true,
                title: '名称',
                width: 160,
                templet: function(d) {
                    var name = d.goodsName;
                    if (isWithinLastSevenDays(d.createTime)) {
                        name = '<span style="color: #001aff; font-weight: bold;">新品</span> ' + name;
                    }
                    return name;
                }
            },
            {field: 'goodsNumber', sort: true, title: '编号'},
            {field: 'goodsPcode69', sort: true, title: '商品码'},
            {field: 'goodsXcode69', sort: true, title: '商品码2'},
            {field: 'goodsHcode69', sort: true, title: '商品码3'},
            {field: 'dismantlingParts', sort: true, title: '是否拆零'},
            {field: 'goodsHelpcode', sort: true, title: '助记码'},
            {field: 'goodsHeavybubble', title: '重泡货'},
            {field: 'goodsSpecs', sort: true, title: '规格'},
            {field: 'goodsBigtype', sort: true, title: '分类'},
            {field: 'goodsBrand', sort: true, title: '品牌'},

            {field: 'jibenUnit', sort: true, title: '基本单位'},
            {field: 'kcUnit', sort: true, title: '库存单位'},
            {field: 'boxSpecs', sort: true, title: '化箱规格'},
            {field: 'kcRate', sort: true, title: '库存换算率'},
            {field: 'cgUnit', sort: true, title: '采购单位'},
            {field: 'cgRate', sort: true, title: '采购换算率'},
            {field: 'pfUnit', sort: true, title: '批发单位'},
            {field: 'pfRate', sort: true, title: '批发换算率'},
            {field: 'psUnit', sort: true, title: '配送单位'},
            {field: 'psRate', sort: true, title: '配送换算率'},
            {field: 'anquanNum', sort: true, title: '安全库存值'},
            {field: 'goodsBottom', sort: true, title: '底'},
            {field: 'goodsLamination', sort: true, title: '叠层'},
            {field: 'goodsTraylayer', sort: true, title: '托层'},
            {field: 'goodsSupportvolume', sort: true, title: '每托存量'},
            {field: 'length', sort: true, title: '长(cm)'},
            {field: 'height', sort: true, title: '高(cm)'},
            {field: 'width', sort: true, title: '宽(cm)'},
            {field: 'goodsWeight', sort: true, title: '采购重量'},
            {field: 'goodsVolume', sort: true, title: '采购体积'},
            {field: 'goodsChargingCg', sort: true, title: '采购价'},
            {field: 'goodsChargingPs', sort: true, title: '配送价'},
            {field: 'goodsChargingPf', sort: true, title: '批发价'},
            {field: 'goodsWarranty', sort: true, title: '保质期'},
            {field: 'goodsXlbId', sort: true, title: '新零帮商品id'},
            {field: 'goodsNodes', sort: true, title: '备注'},
            {field: 'createTime', sort: true, title: '创建时间'},
            {field: 'updateTime', sort: true, title: '修改时间'},
            {field: 'createName', sort: true, title: '创建用户'},
            {field: 'updateName', sort: true, title: '修改用户'},

        ]];
    };


    // 同步商品信息
    $('#pickProducts').click(function () {
        layer.open({
            type: 2,
            title: '同步商品信息',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/hxBasicGoods/pickProducts',
            end: function () {
                table.reload(HxBasicGoods.tableId);
            }
        });
    });

    // 同步商品信息
    $('#pickTcslProducts').click(function () {
        layer.open({
            type: 2,
            title: '同步商品信息',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/hxBasicGoods/pickTcslProducts',
            end: function () {
                table.reload(HxBasicGoods.tableId);
            }
        });
    });

    /**
     * 选择时
     */
    HxBasicGoods.onClickDept = function (e, treeId, treeNode) {
        HxBasicGoods.condition.goodsBigtypedictId = treeNode.id;
        HxBasicGoods.search();
    };

    /**
     * 点击查询按钮
     */
    HxBasicGoods.search = function () {
        var queryData = {};
        queryData['goodsCustomerId'] = $("#goodsCustomerId").val();
        queryData['condition'] = $("#condition").val();
        queryData['goodsBigtypedictId'] = HxBasicGoods.condition.goodsBigtypedictId;
        queryData['goodsBrand'] = $("#goodsBrand").val();
        queryData['dismantlingParts'] = $("#dismantlingParts").val();

        table.reload(HxBasicGoods.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };
    /**
     * 点击批量打印标签按钮
     */
    HxBasicGoods.btnPrint = function () {
        var checkStatus = table.checkStatus(HxBasicGoods.tableId);
        data = checkStatus.data;
        console.log(data)
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            submit = 2
            layer.open({
                type: 2,
                title: '批量打印标签码',
                area: ['900px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/hxBasicGoods/tobtnqrCode?ids='+ids+'&printQuantity='+$("#printQuantity").val(),
                // end: function () {
                // 	if(submit == 1){
                // 		table.reload(HxStoragePutDetailed.tableId);
                // 	}
                // }
            });
        } else {
            layer.alert('请至少选中一条数据');
        }
    };

    $('#btnPrintcs').click(function () {
        HxBasicGoods.btnPrint();
    });
    // 导入
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: '商品导入',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/hxBasicGoods/toimportExcel',
            end: function () {
                table.reload(HxBasicGoods.tableId);
            }
        });
    });

    // 导入
    $('#btnExpimportUpdate').click(function () {
        layer.open({
            type: 2,
            title: '商品更新导入',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/hxBasicGoods/toimportExcelUpdate',
            end: function () {
                table.reload(HxBasicGoods.tableId);
            }
        });
    });
    // 校验商品换算率
    $('#btncheck').click(function () {
        layer.open({
            type: 2,
            title: '校验商品信息',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/hxBasicGoods/check',
            end: function () {
                table.reload(HxBasicGoods.tableId);
            }
        });
    });
    // 校验拆零
    $('#btnchecks').click(function () {
        layer.open({
            type: 2,
            title: '校验拆零商品信息',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/hxBasicGoods/checks',
            end: function () {
                table.reload(HxBasicGoods.tableId);
            }
        });
    });
    /**
     * 弹出添加对话框
     */
    HxBasicGoods.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/hxBasicGoods/add';
    };



    /**
     * 导出excel按钮
     */
    HxBasicGoods.exportExcel = function () {
        var checkRows = table.checkStatus(HxBasicGoods.tableId);
        if (checkRows.data.length > 0) {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        } else {
            var queryData = {};
	        queryData['goodsCustomerId'] = $("#goodsCustomerId").val();
	        queryData['condition'] = $("#condition").val();
	        queryData['goodsBigtypedictId'] = HxBasicGoods.condition.goodsBigtypedictId;
	        queryData['goodsBrand'] = $("#goodsBrand").val();
	        queryData['dismantlingParts'] = $("#dismantlingParts").val();
            $.ajax({
                type: "POST",
                url: Feng.ctxPath + "/hxBasicGoods/listAll",
                dataType:'json',
                data: queryData,
                beforeSend: function () {
                    //弹出加载中
                    index = layer.load(1, {
                        shade: [0.3, '#000'] //0.1透明度的白色背景
                    });
                },
                success: function (data) {
                    checkRows.data = data;
                    table.exportFile(tableResult.config.id, checkRows.data, 'xls');
                    layer.close(index);
                },
                error: function (data) {
                    console.log(data)
                }
            });
        }
    };



    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    HxBasicGoods.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/hxBasicGoods/edit?id=' + data.id;
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    HxBasicGoods.onDeleteItem = function (data) {
        let ajax = new $ax(Feng.ctxPath + "/hxBasicGoods/kucun", function (kucunData) {
            // 执行成功的回调函数
            if (kucunData.success) {
                var operation = function (){
                    // 进行删除操作
                    var deleteAjax = new $ax(Feng.ctxPath + "/hxBasicGoods/delete", function (deleteData) {
			            if (deleteData.success){
	                        Feng.success("删除成功!");
	                        table.reload(HxBasicGoods.tableId);
			            } else {
			                Feng.error("删除失败！" + deleteData.message)
			            }
                    }, function (deleteData) {
                        Feng.error("删除失败!" + deleteData.responseJSON.message + "!");
                    });
                    deleteAjax.set("id", data.id);
                    deleteAjax.start();
                    }
                Feng.confirm("是否删除?", operation);
            } else {
                // 库存不足
                Feng.error(kucunData.message);
            }
        }, function (errorData) {
            // 出错的回调函数
            Feng.error("请求库存信息失败!" + errorData.responseJSON.message);
        });
        ajax.set("goodsId", data.id);
        ajax.start();
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + HxBasicGoods.tableId,
        url: Feng.ctxPath + '/hxBasicGoods/list',
        page: true,
        limit: 40,
        height: "full-60",
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        cols: HxBasicGoods.initColumn()
    });

    //初始化左侧部门树
    var ztree = new $ZTree("deptTree", "/hxBasicGoodsCode/treeo");
    ztree.bindOnClick(HxBasicGoods.onClickDept);
    ztree.init();

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        HxBasicGoods.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        HxBasicGoods.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        HxBasicGoods.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + HxBasicGoods.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            HxBasicGoods.openEditDlg(data);
        } else if (layEvent === 'delete') {
            HxBasicGoods.onDeleteItem(data);
        } else if (obj.event === 'paymentProve') {
  	    	//构建图像数组
      		var items = [];
        	if (data.v1!='') {
        		var obj = {};
        		obj.src = '/system/previewa/' + data.v1;
        		obj.title = '预览图片';
        		items.push(obj)
    	      	//定义选项（如果需要）
    	      	var options = {
    	      	    index: 0 // 此选项表示您将从第一张图片开始
    	      	};
    	      	//初始化插件
    	      	var viewer = new PhotoViewer(items, options);
			} else {
                Feng.info("暂无照片!");
			}
        }
    });
});
